package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

func MyMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 在请求前处理
		t := time.Now()

		// 请求前
		c.Set("example", "12345")

		// 请求后
		c.Next()

		// 在请求后处理
		latency := time.Since(t)
		log.Print(latency)

		// 访问状态码
		status := c.Writer.Status()
		log.Println(status)
	}
}

type Login struct {
	User     string `json:"user" form:"user" binding:"required"`
	Password string `json:"password" form:"password" binding:"required"`
}

func main() {

	router := gin.Default() // 默认包含Logger和Recovery中间件

	// json 返回
	router.GET("/ping", func(c *gin.Context) {
		// query 参数
		id := c.Query("id")
		name := c.DefaultQuery("name", "Mike")
		fmt.Println(id, name)

		c.JSON(http.StatusOK, gin.H{
			"message": "pong"})
	})

	// 路由参数
	router.GET("/user/:name", func(c *gin.Context) {

		name := c.Param("name")
		c.String(http.StatusOK, "Hello %s", name)
	})

	// json参数
	router.POST("/loginJSON", func(c *gin.Context) {
		var json Login
		if err := c.ShouldBindJSON(&json); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		if json.User != "user" || json.Password != "password" {
			c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			return
		}

		c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
	})

	// 表单参数
	router.POST("/loginForm", func(c *gin.Context) {
		var form Login
		if err := c.ShouldBind(&form); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		if form.User != "user" || form.Password != "password" {
			c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
			return
		}

		c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
	})

	// 单文件上传
	router.POST("/upload", func(c *gin.Context) {
		file, _ := c.FormFile("file")
		log.Println(file.Filename)

		c.SaveUploadedFile(file, "./upload/"+file.Filename)

		c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
	})

	// 多文件上传
	router.POST("/uploadMultiple", func(c *gin.Context) {
		form, _ := c.MultipartForm()
		files := form.File["files"]

		for _, file := range files {
			log.Println(file.Filename)
			c.SaveUploadedFile(file, "./upload/"+file.Filename)
		}
		c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
	})

	router.GET("/download", func(c *gin.Context) {
		//设置header属性值
		c.Header("Content-Type", "application/octet-stream")
		// 用来指定下载下来的文件名
		c.Header("Content-Disposition", "attachment; filename="+"test.txt")
		filePath := "D:\\images\\211.txt"

		c.File(filePath)
	})

	router.Use(MyMiddleware())
	router.Run(":8080") // 默认监听端口号:8080

}
